package com.cashmama.market.api.domain.service;

import com.alibaba.fastjson.JSON;
import com.cashmama.market.api.domain.integration.AdvanceAiIntegrationService;
import com.cashmama.market.api.domain.vo.aadhaar.OcrCardResultVO;
import com.cashmama.market.api.domain.vo.aadhaar.OcrResponseVO;
import com.cashmama.market.api.infras.config.ApolloConfigUtil;
import com.cashmama.market.api.infras.exception.ApplicationException;
import com.cashmama.market.api.infras.utils.DateUtil;
import com.fqgj.base.services.amazon.AmazonS3Service;
import com.fqgj.base.services.oss.OSSService;
import com.fqgj.common.api.Response;
import com.fqgj.xjd.user.client.UserInfoService;
import com.fqgj.xjd.user.client.UserOcrInfoService;
import com.fqgj.xjd.user.client.enums.UserOcrTypeEnum;
import com.fqgj.xjd.user.client.request.UserOcrInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: market-api
 * @description 异步处理
 * @author: frank
 * @create: 2020-01-02 14:21
 **/
@Service
public class AsyncService {
    private final static Logger LOGGER = LoggerFactory.getLogger(AsyncService.class);

    @Autowired
    private AdvanceAiIntegrationService advanceAiIntegrationService;
    @Autowired
    private ApolloConfigUtil apolloConfigUtil;
    @Autowired
    private OSSService ossService;
    @Autowired
    private UserOcrInfoService userOcrInfoService;
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private AmazonS3Service amazonS3Service;

    public String asyncOcr(UserOcrTypeEnum userOcrTypeEnum, String imgUrl, String userCode) {
        LOGGER.info("apolloConfigUtil.openApiOcr:{}", apolloConfigUtil.openApiOcr());
        if (!apolloConfigUtil.openApiOcr()) {
            return null;
        }
        Response<String> ocrResponse = advanceAiIntegrationService.ocr(imgUrl);
        LOGGER.info("ocrResponse ocrResponse:{}", ocrResponse);
        if (!ocrResponse.isSuccess()) {
            LOGGER.info("ocrResponse error : userCode:{}", userCode);
            throw new ApplicationException(apolloConfigUtil.getPanCardOcrTip());
        }

        String ocrData = ocrResponse.getData();
        //上传数据到oss
        String fileName = "ocr/%s/%s_%s.json";
        fileName = String.format(fileName, userOcrTypeEnum.name(), userCode, DateUtil.getDate(new Date()));
        String dataUrl = apolloConfigUtil.getQsyqBaseUrl() + ossService.uploadFile(fileName, ocrData);

        UserOcrInfo userOcrInfo = new UserOcrInfo();
        userOcrInfo.setUserCode(userCode);
        userOcrInfo.setOcrResultUrl(dataUrl);
        userOcrInfo.setOcrType(userOcrTypeEnum);
        userOcrInfoService.saveUserOcrInfo(userOcrInfo);

        return ocrData;
    }

    /**
     * advance家的ocr接口
     *
     * @param userOcrTypeEnum
     * @param frontImgUrl
     * @param backImgUrl
     * @param userCode
     * @return
     */
    public String asyncOcrV3(UserOcrTypeEnum userOcrTypeEnum, String frontImgUrl, String backImgUrl, String userCode) {
        boolean isAadhaar = userOcrTypeEnum.equals(UserOcrTypeEnum.AADHAAR_BACK) || userOcrTypeEnum.equals(UserOcrTypeEnum.AADHAAR_FRONT);
        String cardType = isAadhaar ? "aadhaar_card" : "pan_card";
        boolean isFront = userOcrTypeEnum.equals(UserOcrTypeEnum.AADHAAR_FRONT) || userOcrTypeEnum.equals(UserOcrTypeEnum.PAN_FRONT);
        String cardSide = isFront ? "front" : "back";

        if (isAadhaar) {
            Response<OcrResponseVO> ocrResponseVoResponse = advanceAiIntegrationService.ocrAadhaar(frontImgUrl, backImgUrl);
            if (!ocrResponseVoResponse.isSuccess()) {
                LOGGER.error("== save card exception ==, aadhaar orc failed,msg:{}", ocrResponseVoResponse.getMsg());
                throw new ApplicationException(ocrResponseVoResponse.getMsg());
            }
            OcrResponseVO data = ocrResponseVoResponse.getData();
            OcrResponseVO frontOcr = composeOcr(data, cardType, cardSide);
            String ocrData = JSON.toJSONString(frontOcr);
            store(userCode, userOcrTypeEnum, ocrData, "advance");

            OcrResponseVO aadhaarBackOcr = composeOcr(data, cardType, "back");
            store(userCode, UserOcrTypeEnum.AADHAAR_BACK, JSON.toJSONString(aadhaarBackOcr), "advance");
            return ocrData;
        } else {

            Response<OcrResponseVO> ocrResponseVoResponse = advanceAiIntegrationService.ocrPan(frontImgUrl);
            if (!ocrResponseVoResponse.isSuccess()) {
                LOGGER.error("== save card exception ==,pan orc failed,msg:{}", ocrResponseVoResponse.getMsg());
                throw new ApplicationException(ocrResponseVoResponse.getMsg());
            }
            OcrResponseVO data = ocrResponseVoResponse.getData();
            OcrResponseVO frontOcr = composeOcr(data, cardType, cardSide);
            String ocrData = JSON.toJSONString(frontOcr);
            store(userCode, userOcrTypeEnum, ocrData, "advance");
            return ocrData;
        }

//        [RupeeMama] limited time benefits for borrowing again today, up to 55000 Rs. 90% pass rate. click https://bit.ly/3DpLV6l . Vasuki Information


    }

    public OcrResponseVO composeOcr(OcrResponseVO baseData, String cardType, String cardSide) {
        OcrResponseVO data = new OcrResponseVO();
        BeanUtils.copyProperties(baseData, data);

        OcrCardResultVO resultVo = baseData.getResults().get(0);
        resultVo.setCard_type(cardType)
                .setCard_side(cardSide);

        List<OcrCardResultVO> results = new ArrayList<>();
        results.add(resultVo);
        data.setResults(results);

        LOGGER.info("== ocr内容 ==,cardType:{},content:{}", cardType, JSON.toJSONString(data));
        return data;
    }

    /**
     * 上传数据到oss
     *
     * @param userCode
     * @param userOcrTypeEnum
     * @param data
     */
    private void store(String userCode, UserOcrTypeEnum userOcrTypeEnum, String data, String providerType) {
        //上传数据到oss
        String fileName = "ocr/%s/%s_%s.json";
        fileName = String.format(fileName, userOcrTypeEnum.name(), userCode, DateUtil.getDate(new Date()));
//        String dataUrl = apolloConfigUtil.getQsyqBaseUrl() + ossService.uploadFile(fileName, data);
        ossService.uploadFile(fileName, data);
        String dataUrl = apolloConfigUtil.getOssBaseUrl() + fileName;

        LOGGER.info("上传文件的url,userCode:{},dataUrl:{},data:{}", userCode, dataUrl, data);
        UserOcrInfo userOcrInfo = new UserOcrInfo();
        userOcrInfo.setUserCode(userCode);
        userOcrInfo.setOcrResultUrl(dataUrl);
        userOcrInfo.setOcrType(userOcrTypeEnum)
                .setProviderType(providerType);
        userOcrInfoService.saveUserOcrInfo(userOcrInfo);
    }


}
